package com.happystudy.serviceImpl;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.happpystudy.model.User;
import com.happpystudy.model.course.Course;
import com.happpystudy.model.course.CourseKey;
import com.happpystudy.model.course.CourseTeacher;
import com.happpystudy.service.CourseTeacherService;
import com.happystudy.mapper.CourseTeacherMapper;
import com.happystudy.util.KeyUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class CourseTeacherServiceImpl implements CourseTeacherService {

    @Resource
    CourseTeacherMapper courseTeacherMapper;

    @Resource
    RedisTemplate redisTemplate;

    @Resource
    UserServiceImpl userService;

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int insertSelective(CourseTeacher courseTeacher) {

        return courseTeacherMapper.insertSelective(courseTeacher);
    }

    @Override
    public List<User> selectAllUserByCourseKey(CourseKey courseKey){
        List<User> users = new ArrayList<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(CourseTeacher.class));
        String key = KeyUtil.COURSE_TEACHER_BY_COURSE_KEY+":"+courseKey.getUniId()+courseKey.getCourseId()+courseKey.getCourseGroup();
        Set<CourseTeacher> courseTeacherSet =  redisTemplate.opsForSet().members(key);
        List<CourseTeacher> courseTeachers = new ArrayList<>();
        if (courseTeacherSet!=null){
            courseTeachers = new ArrayList<>(courseTeacherSet);
        }


        if (courseTeachers.size() == 0){
             courseTeachers = courseTeacherMapper.selectByCourseKey(courseKey);
             if (courseTeachers!=null && courseTeachers.size()!=0){
                 for (CourseTeacher courseTeacher:courseTeachers){
                     redisTemplate.opsForSet().add(key,courseTeacher);
                 }
             }
        }

        if (courseTeachers==null){
            return users;
        }
        for (CourseTeacher courseTeacher:courseTeachers){
            User user = userService.queryUserByUserId(courseTeacher.getUserId());
            users.add(user);
        }
        return users;
    }
}
